import React, { PropTypes, PureComponent } from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Tooltip } from 'antd';
import { PrimaryC, TableC } from '../../comps';
import moment from 'moment/moment';
@Form.create()
class TrialTrade extends PureComponent {
  state = {
    currentPage: 1, // 当前页码
    pageSize: 10, // 一页数量
    total: 0, // 数据总数
    dataSource: [],
  };

  componentDidMount() {
    this.props.onRef(this);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {}

  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }

  //新建试算交易
  addClick = () => {
    this.props.addNewChange();
  };

  refresh = () => {
    this.setState(
      {
        currentPage: 1,
        pageSize: 10,
      },
      () => {
        this.getList();
      },
    );
  };

  //删除交易
  deleteAccount = (id, e) => {
    e.preventDefault();
    this.props.dispatch({
      type: 'portfolioTrialM/deleteTrade',
      payload: {
        id,
      },
      callback: (data) => {
        message.success('删除成功');
        this.refresh();
      },
    });
  };

  //获取表格数据
  getList = () => {
    const { pageSize, currentPage } = this.state;
    const { dataObj } = this.props;
    this.props.dispatch({
      type: 'portfolioTrialM/getList',
      payload: {
        groupId: dataObj.productGroup,
        portfolioCodes: dataObj.product.length > 0 ? dataObj.product : undefined,
        templateId: dataObj.template,
        currentPage: currentPage,
        numInPage: pageSize,
      },
      callback: (data) => {
        if (data && data.dataSource.length) {
          this.changeColumns(data.columns);
          this.setState({
            columns: data.columns,
            dataSource: data.dataSource.filter((i) => i?.isTrialferBook !== 'Y'),
            currentPage: data.pageInfo.currentPage,
            total: data.pageInfo.total,
            pageSize: data.pageInfo.pageSize,
          });
        } else {
          this.setState({
            dataSource: [],
            columns: [],
            total: 0,
            currentPage: 1,
            pageSize: 10,
          });
        }
      },
    });
  };

  //表格页码排序改变调用
  handleTableChange = (pagination) => {
    const { dataObj } = this.props;
    if (dataObj.isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        pageSize: pageSize,
      },
      () => {
        this.getList();
      },
    );
  };

  /***
   * 点击试算
   * @param {string} id
   * @param {event} e
   */
  virtualTrialCalculation = (id, e) => {
    e.preventDefault();
    // 父组件查询 方便调用兄弟组件
    this.props.visualTryCompute(id);
  };
  //添加操作列
  changeColumns = (columns) => {
    columns.map((v) => {
      if (v.key === 'tradingCode') {
        v.render = (text, record) => {
          if (record.type == '26') {
            return (
              <>
                {text}{' '}
                <Tooltip title={`虚拟债券标的`}>
                  <QuestionCircleOutlined />
                </Tooltip>
              </>
            );
          }
          return text;
        };
      }
      if (v.key === 'tradingName') {
        v.render = (text, record) => {
          if (record.type == '26') {
            const getTradingNameTips = () => {
              const { timeLimit, subjectrating, bondrating, bondType } = record[`trade${record.type}`];
              return (
                <div>
                  <span>{timeLimit && `期限：${timeLimit}`}</span> <span>{subjectrating && `主体评级：${subjectrating}`}</span>{' '}
                  <span>{bondrating && `债项评级：${bondrating === 'NOT_RATED' ? '无评级' : bondrating}`}</span> <span>{bondType && `债券类型：${bondType}`}</span>
                </div>
              );
            };
            return (
              <>
                {text}{' '}
                <Tooltip title={getTradingNameTips()}>
                  <QuestionCircleOutlined />
                </Tooltip>
              </>
            );
          }
          return text;
        };
      }
    });
    if (columns.length && columns[columns.length - 1].title != '操作') {
      columns.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        fixed: 'right',
        width: 120,
        render: (text, record) => {
          return (
            <div>
              {record.type == 26 ? (
                moment(record.createdTs).format('YYYY-MM-DD') === moment().format('YYYY-MM-DD') ? null : (
                  <a
                    onClick={(event) => {
                      this.virtualTrialCalculation(record.id, event);
                    }}
                  >
                    试算
                  </a>
                )
              ) : null}
              <a
                disabled={record.instructionStatus == '7' || record.instructionStatus == '8'}
                onClick={(event) => {
                  this.deleteAccount(record.id, event);
                }}
              >
                删除
              </a>
            </div>
          );
        },
      });
    }
  };

  render() {
    let { columns, dataSource, total, currentPage, pageSize } = this.state;
    return (
      <div>
        <PrimaryC onClick={this.addClick} title='新建' />
        <div style={{ marginTop: '10px' }}>
          <TableC
            columns={columns}
            loading={this.props.loading}
            dataSource={dataSource}
            current={currentPage}
            selfScrollY={true}
            pageSize={pageSize}
            total={total}
            rowKey='id'
            pagination={true}
            onChange={this.handleTableChange}
            scroll={{ x: 'max-content' }}
          />
        </div>
      </div>
    );
  }
}
export default connect(({ portfolioTrialM, loading }) => ({ portfolioTrialM, loading: loading.effects['portfolioTrialM/getList'] }))(TrialTrade);
